<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="临时任务名称" required prop="name">
            <el-input v-model="formItem.name" placeholder="请输入临时任务名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维护部门" required prop="orgCode">
            <treeselect
              v-model="formItem.orgCode"
              :multiple="false"
              :options="availableOganizations"
              placeholder="请选择部门"
              @select="selcetOrg"
              @input="inputOrg"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="执行人" prop="chargeUserName">
            <el-input v-model="formItem.chargeUserName" placeholder="请选择执行人" @focus="handleUserIconClick" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <!-- <el-col :span="8">
          <el-form-item label="维护开始时间" prop="startDateTime">
            <el-date-picker
              v-model="formItem.startDateTime"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维护结束时间" prop="endDateTime">
            <el-date-picker
              v-model="formItem.endDateTime"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="维护类别" required prop="modelCode">
            <treeselect
              v-model="formItem.modelCode"
              :multiple="false"
              :options="cmdbModels"
              :load-options="loadOptions"
              :disable-branch-nodes="true"
              id-key="code"
              label-key="name"
              placeholder="请选择维护类别"
              @select="selModel"
              @input="selModelInput"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="量化时间(小时)" prop="quantifyingTime">
            <el-input-number v-model="formItem.quantifyingTime" :precision="0" :step="1" :max="10000" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否停止服务" prop="suspendService">
            <el-radio v-model="suspendService" :label="true" @change="changeSuspendService">是</el-radio>
            <el-radio v-model="suspendService" :label="false" @change="changeSuspendService">否</el-radio>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="维护规则" prop="ruleCode">
            <el-select v-model="formItem.ruleCode" class="select_input" placeholder="请选择规则" @focus="ruleClick">
              <el-option v-for="(item) in maintainRuleList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item label="维护对象" prop="instancesArray">
            <div style="margin-bottom: 5px; float: right!important;">
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleSelectInstances">添加</el-button>
              <el-button type="primary" size="mini" icon="el-icon-delete" @click="handleRemove">移除</el-button>
            </div>
            <div class="anthor-info-body">
              <div class="table-app-container">
                <div class="fixed-table">
                  <PageableTable
                    :data="formItem.instancesArray"
                    :loading="false"
                    :table-height="260"
                    :disable-pageable="true"
                    :multiple-selected="true"
                    class="fixed-table-table"
                    @selection-change="tableSelection"
                  >
                    <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
                      <template slot-scope="scope">
                        <column-render :render="column.render" :row="scope.row" :column="column" />
                      </template>
                    </el-table-column>
                  </PageableTable>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="是否生成规则" prop="createRule">
            <el-radio v-model="createRule" :label="true" @change="changeCreateRule">是</el-radio>
            <el-radio v-model="createRule" :label="false" @change="changeCreateRule">否</el-radio>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item v-show="showDesc" label="维护说明" prop="description">
            <Tinymce v-show="showDesc" v-model="formItem.description" :height="300" menubar="false" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <SelectDialog v-if="userSelDialogFormVisible" title="选择执行人" :append-to-body="true" :show="userSelDialogFormVisible" @on-ok="selectUserOk" @on-cancel="selectUserCancel">
      <UsersPage ref="usersTable" :for-selection="true" :multiple-selected="true" :org-code="formItem.orgCode" />
    </SelectDialog>
    <SelectDialog v-if="instanceSelDialogFormVisible" title="选择维护对象" width="60%" :append-to-body="true" :show="instanceSelDialogFormVisible" @on-ok="selectInstanceOk" @on-cancel="selectInstanceCancel">
      <instancesTable ref="instancesTable" :for-selection="true" :model-code="formItem.modelCode" />
    </SelectDialog>
  </div>
</template>

<script>
import Vue from 'vue'
import { listByModelCodeAndStatus } from '@neu/dcom-ui/api/maintainRule'
// import { formatDate } from '@neu/biz-core/utils/utils'
import {
  create,
  update,
  detail
} from '@neu/dcom-ui/api/maintainTask'
import Tinymce from '@neu/biz-core/components/Tinymce'
import UsersPage from '@neu/auth-ui/views/users/tables'
import * as organizations from '@neu/auth-ui/api/organization'
import { pureTree } from '@neu/dcom-ui/api/schema'
import instancesTable from '@neu/dcom-ui/views/instances/tables'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import PageableTable from '@neu/biz-core/components/PageableTable'

// 定义一个表单原始项
const formItem = {
  name: '',
  code: '',
  orgCode: null,
  orgName: '',
  chargeUserId: '',
  chargeUserCode: '',
  chargeUserName: '',
  suspendService: true,
  modelCode: null,
  modelName: '',
  objCode: '',
  objName: '',
  ruleCode: '',
  ruleName: '',
  status: 'undo',
  // startDateTime: '',
  // endDateTime: '',
  noticeSendStatus: null,
  source: 'temporary',
  ruleSource: 'temporary',
  createRule: false,
  description: '',
  instancesArray: [],
  jsonObjs: '',
  quantifyingTime: 0
}
export default {
  name: 'MaintainTaskEditForm',
  components: {
    Tinymce,
    UsersPage,
    SelectDialog,
    instancesTable,
    PageableTable
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      /** CMDB模型树 */
      cmdbModels: null,
      /** CMDB实例 */
      cmdbInstances: null,
      /** 是否显示用户选择对话框 */
      userSelDialogFormVisible: false,
      /** 部门 */
      availableOganizations: [],
      /** 是否显示实例 */
      instanceSelDialogFormVisible: false,
      /** 启用状态 */
      status: [],
      // 运维规则
      maintainRuleList: [],
      /** 要移除的对象 */
      removeData: [],
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 表单验证规则
      rules: {
        name: [{
          required: true,
          message: '名称不能为空',
          trigger: 'blur'
        },
        {
          validator: function(rule, value, callback) {
            if (value.length > 100) {
              callback(new Error('最多可输入100个字符'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        orgCode: [{
          required: true,
          message: '维护部门不能为空',
          trigger: 'blur'
        }],
        chargeUserName: [{
          required: true,
          message: '执行人不能为空',
          trigger: 'blur'
        }],
        modelCode: [{
          required: true,
          message: '维护类别不能为空',
          trigger: 'blur'
        }],
        instancesArray: [{
          required: true,
          message: '维护对象不能为空',
          trigger: 'blur'
        }]
        // startDateTime: [{
        //   required: true,
        //   message: '开始时间不能为空',
        //   trigger: 'blur'
        // }],
        // endDateTime: [{
        //   required: true,
        //   message: '结束时间不能为空',
        //   trigger: 'blur'
        // }]
      },
      dialogViewRuleVisible: false,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      insideColumns: [
        // { title: 'ID', key: '_id' },
        { title: '唯一标识', key: 'code' },
        { title: '名称', key: 'name' }
        // { title: '模型', key: 'schemadefName' }
      ],
      /** 是否需要停止服务  */
      suspendService: true,
      /** 是否生成维护规则  */
      createRule: false,
      /** 是否显示维护说明  */
      showDesc: false,
      /** 是否初始化 */
      isUpdateInit: true
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.fetch()
    organizations.tree().then(response => {
      this.availableOganizations = [response.data]
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.isUpdateInit = false
          this.formItem = {
            ...response.data
          }
          this.createRule = this.formItem.createRule
          this.showDesc = this.formItem.createRule
          this.formItem.instancesArray = JSON.parse(this.formItem.jsonObjs)
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save(value) {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            this.formItem.jsonObjs = JSON.stringify(this.formItem.instancesArray)
            this.formItem.status = value
            // if (formatDate(this.formItem.startDateTime) > formatDate(this.formItem.endDateTime)) {
            //   return this.$message({
            //     showClose: true,
            //     message: '任务开始时间不能大于任务结束时间',
            //     type: 'error'
            //   })
            // }
            this.formItem.objCode = this.formItem.instancesArray[0].code
            this.formItem.objName = this.formItem.instancesArray[0].name
            if (!this.showDesc) {
              this.formItem.description = ''
            }

            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
      this.formItem.instancesArray = []
      this.formItem = { ...formItem }
    },
    loadOptions({ action }) {
      if (action === 'LOAD_ROOT_OPTIONS') {
        return pureTree().then(response => {
          this.cmdbModels = response.data
        })
      }
    },
    /** 选择用户按钮 */
    handleUserIconClick() {
      if (!this.formItem.orgCode) {
        this.$message({
          type: 'warning',
          message: '请选择部门!'
        })
        return
      }
      this.userSelDialogFormVisible = true
    },
    selectUserOk() {
      var users = this.$refs.usersTable.selections
      if (users.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个用户',
          type: 'error'
        })
      }
      if (users.length < 1) {
        this.formItem.chargeUserId = ''
        this.formItem.chargeUserCode = ''
        this.formItem.chargeUserName = ''
      } else {
        this.formItem.chargeUserId = users[0].id
        this.formItem.chargeUserName = users[0].name ? users[0].name : users[0].username
        this.formItem.chargeUserCode = users[0].username
      }
      this.userSelDialogFormVisible = false
    },
    selectUserCancel() {
      this.userSelDialogFormVisible = false
    },
    changeSuspendService(value) {
      this.formItem.suspendService = value
    },
    changeCreateRule(value) {
      this.formItem.createRule = value
      this.showDesc = value
    },
    selModel(node) {
      if (this.formItem.modelCode !== node.code) {
        this.formItem.instancesArray = []
      }
      this.formItem.modelName = node.name
      this.formItem.modelCode = node.code

      this.formItem.ruleName = ''
      this.formItem.ruleCode = ''
    },
    selModelInput(value) {
      listByModelCodeAndStatus(value, 'enable').then(response => {
        this.maintainRuleList = response.data
      })
    },
    ruleClick() {
      if (!this.formItem.modelCode) {
        this.$message({
          type: 'warning',
          message: '请选择维护类别'
        })
        return
      }
    },
    /** 选择对象 */
    handleSelectInstances() {
      if (!this.formItem.modelCode) {
        this.$message({
          type: 'warning',
          message: '请选择维护类别'
        })
        return
      }
      this.instanceSelDialogFormVisible = true
    },
    /** 删除某一项 */
    handleRemove() {
      if (this.removeData.length === 0) {
        return this.$message({
          showClose: true,
          message: '请选择一个对象',
          type: 'error'
        })
      }

      this.removeData.forEach(t => {
        this.formItem.instancesArray.forEach((item, index) => {
          if (item.code === t) {
            Vue.delete(this.formItem.instancesArray, index)
          }
        })
      })
    },
    tableSelection(sel) {
      this.removeData = sel.map(a => a.code)
    },
    selectInstanceOk() {
      const instances = this.$refs.instancesTable.selections
      if (instances.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个对象',
          type: 'error'
        })
      }
      const instanceCodes = this.formItem.instancesArray.map(a => a.code)
      const difference = instances.filter(t => {
        return !instanceCodes.includes(t.code)
      })
      this.formItem.instancesArray.push(...difference)
      this.instanceSelDialogFormVisible = false
    },
    selectInstanceCancel() {
      this.instanceSelDialogFormVisible = false
    },
    /** 组织机构赋值 */
    selcetOrg(value) {
      this.formItem.orgName = value.title

      this.formItem.chargeUserId = ''
      this.formItem.chargeUserCode = ''
      this.formItem.chargeUserName = ''
    },
    inputOrg(value) {
      if (this.isUpdateInit) {
        this.formItem.chargeUserId = ''
        this.formItem.chargeUserCode = ''
        this.formItem.chargeUserName = ''
      }
      this.isUpdateInit = true
      if (value === undefined) {
        this.formItem.orgName = ''
      }
    }
  }

}
</script>
